/**
 * Copyright &copy; 2015-2020 <a href="www.dsesa.cn/">ESA</a> All rights reserved.
 */
package com.jeeplus.modules.wxMsg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.utils.LogUtils;
import com.jeeplus.modules.wxMsg.entity.WxResult;
import org.activiti.engine.impl.persistence.entity.TaskEntity;

import java.util.Date;
import java.util.Map;

public  class SendWX {

	public static final int agentId = Integer.parseInt(Global.getConfig("agentId"));

	public static void send(String userName,String msg,TaskEntity taskEntity) {
		WeChatMsgSend swx = new WeChatMsgSend();
		try {
			if(StringUtils.isNotBlank(userName)){
				String token = swx.getCurrToken();
				if(StringUtils.isBlank(token)){
					token = swx.getToken();
				}
				String postdata = swx.createpostdata(userName, "text", agentId, "content", msg);
				String resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, token);
				Gson gson = new Gson();
				Map<String, Object> map = gson.fromJson(resp, new TypeToken<Map<String, Object>>() {
				}.getType());
				if("42001.0".equals(map.get("errcode").toString())){
					token = swx.getToken();
					resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE, (new WeChatUrlData()).getSendMessage_Url(), postdata, token);
				}
				JSONObject json = JSON.parseObject(resp);
				WxResult wxResult = new WxResult();
				wxResult.setId(IdGen.uuid());
				wxResult.setCreateDate(new Date());
				wxResult.setErrcode(json.getString("errcode"));
				wxResult.setErrmsg(json.getString("errmsg"));
				wxResult.setTaskEntity(taskEntity);
				wxResult.setToUser(userName);

				LogUtils.saveWxSendLog(wxResult);
				System.out.println("获取到的token======>" + token);
				System.out.println("请求数据======>" + postdata);
				System.out.println("发送微信的响应数据======>" + resp);
			}else {
				WxResult wxResult = new WxResult();
				wxResult.setId(IdGen.uuid());
				wxResult.setCreateDate(new Date());
				wxResult.setErrcode("1002");
				wxResult.setErrmsg("微信账号未设置");
				wxResult.setTaskEntity(taskEntity);
				wxResult.setToUser(userName);
				LogUtils.saveWxSendLog(wxResult);
			}

		} catch (Exception e) {
			e.getStackTrace();
		}
	}

}